<template>
  <!-- start 产品模板列表 -->
  <div class="product-template-list-view" ref="productTemplateListPage">
    <!-- start 搜索 -->
    <div class="product-template-list-search-group">
      <!-- start  搜索header -->
      <form
        class="base-search"
        @submit.prevent="searchModel.pageNum=1;search();"
      >
        <div class="product-template-list-base-search-group">
          <el-input v-model="searchModel.keyword" placeholder="请输入手机号或关联编号">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <base-button type="primary" native-type="submit">搜索</base-button>
          <base-button type="ghost" @event="resetParams">重置</base-button>
        </div>
        <span class="advanced-search-visible-btn" @click.stop="panelSearchAdvancedToggle">
          <i class="iconfont icon-add"></i>
          高级搜索
        </span>
      </form>
      <!-- end 搜索 header -->

      <!-- start 高级搜索表单 -->
      <product-template-search-panel
        :config="{
          fields: this.smsSendFields,
        }"
        ref="searchPanel"
      >
        <div class="advanced-search-btn-group" slot="footer">
          <base-button type="ghost" @event="resetParams">重置</base-button>
          <base-button type="primary" @event="powerfulSearch" native-type="submit">搜索</base-button>
        </div>
      </product-template-search-panel>
      <!-- end 高级搜索表单 -->
    </div>
    <!-- end 搜索 -->

    <!-- start content -->
    <div class="product-template-list-content">

      <!-- start 表格 -->
      <el-table
        :data="page.list"
        :row-key="getRowKey"
        stripe
        border
        :highlight-current-row="false"
        header-row-class-name="product-template-table-header"
        ref="productTemplateTable"
        class="product-template-table"
      >
        <el-table-column
          v-for="column in columns"
          v-if="column.show"
          :key="column.field"
          :label="column.label"
          :prop="column.field"
          :width="column.width"
          :min-width="column.minWidth || '120px'"
          :sortable="column.sortable"
          show-overflow-tooltip
          :align="column.align"
        >
          <template slot-scope="scope">
            <template v-if="column.field === 'operation'">{{ getChiType(scope.row.operation)}}</template>
            <template v-else-if="column.field === 'status'">
              <p
                :class="conversionStatus[scope.row.status] ? conversionStatus[scope.row.status]['className'] : ''"
              >{{ conversionStatus[scope.row.status] ? conversionStatus[scope.row.status]['text'] : ''}}</p>
            </template>
            <template v-else-if="column.field === 'sendTime'">{{ scope.row.sendTime | fmt_datetime }}</template>
            <template v-else>{{scope.row[column.field]}}</template>
          </template>
        </el-table-column>
      </el-table>
      <!-- end 表格 -->

      <!-- start 表格底部 -->
      <div class="table-footer">
        <div class="list-info">
          共
          <span class="level-padding">{{ page.total || 0 }}</span>记录
        </div>
        <el-pagination
          class="product-template-table-pagination"
          background
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="page.pageSize"
          :current-page="page.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="page.total"
        ></el-pagination>
      </div>
      <!-- end 表格底部 -->
    </div>
    <!-- end content -->
    
    <base-table-advanced-setting ref="advanced" @save="columnStatusModify" />

  </div>
  <!-- end 产品模板列表 -->
</template>

<script>
import Page from '@model/Page';
import { formatDate, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import SearchPanel from '../../../toastList/components/SearchPanel.vue';
import { getTemplates, getRecords } from '@src/api/DoMyself.js';
import { defaultTableData } from '@src/util/table'
/* 高级搜索面板 列数 */
const PRODUCT_TEMPLATE_LIST_ADVANCE_SEARCH_COLUMN_NUMBER = 'customer_contact_search_column_number';
// 产品模板列表数据
const PRODUCT_TEMPLATE_LIST_DATA = 'product_template_list_data';

let startTime = +nearDateBy(6, 'day');
let endTime = +dayTimeEnd()

export default {
  name: 'sms-send-record',
  data() {
    return {
      defaultTableData,
      columns: this.buildTableFixedColumns(), // 列
      columnNum: 1, // 高级搜索 列数
      page: new Page(), // page 对象
      searchModel: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
        startTime,
        endTime,
        orderDetail: {},
        moreConditions: {}
      },
      conversionStatus: {
        fail_send: {
          text: '发送失败',
          value: 'fail_send',
          className: 'error-text'
        },
        succ_send: {
          text: '发送成功',
          value: 'succ_send',
          className: 'success-text'
        },
        doing_send: {
          text: '发送中',
          value: 'doing_send',
          className: 'loading-text'
        }
      },
    };
  },
  computed: {
    smsSendFields() {
      return (
        [
          {
            displayName: '通知类型',
            fieldName: 'operation',
            formType: 'select',
            placeHolder: '请选择通知类型',
            isExport: false,
            setting: {
              isMulti: false,
              dataSource: [
                {
                  text: '全部类型',
                  value: ''
                },
                {
                  text: '工单响应通知',
                  value: 'taskResponseHandle'
                },
                {
                  text: '工单完成通知（回访）',
                  value: 'autoReviewHandle'
                },
                {
                  text: '工单动态更新通知',
                  value: 'taskRemarkEdit'
                },
                {
                  text: '新建事件通知',
                  value: 'eventCreateHandle'
                },
                {
                  text: '事件完成通知',
                  value: 'eventFinishHandle'
                },
                {
                  text: '定时通知',
                  value: 'remindMessageHandle'
                },
                {
                  text: '计划时间通知',
                  value: 'taskPlanSmsRemindHandle'
                },
                {
                  text: '客户短信提醒',
                  value: 'sendSms2Cus'
                },
                {
                  text: '产品短信提醒',
                  value: 'sendSms2CusByPro'
                },
                {
                  text: '自助门户验证码',
                  value: 'SSP'
                },
                {
                  text: '验证码',
                  value: 'SuperAdmin'
                }
              ]
            },
            isSystem: 1,
            orderId: 1
          },
          {
            displayName: '手机号码',
            fieldName: 'phone',
            formType: 'text',
            placeHolder: '请输入手机号',
            isExport: false,
            isSystem: 1,
            orderId: 2
          },
          {
            displayName: '模板名称',
            fieldName: 'templateId',
            formType: 'select',
            placeHolder: '请选择模板',
            isExport: false,
            setting: {
              isMulti: false,
              dataSource: []
            },
            isSystem: 1,
            orderId: 3
          },
          {
            displayName: '关联编号',
            fieldName: 'relevanceNumber',
            formType: 'text',
            placeHolder: '请输入关联编号',
            isExport: false,
            isSystem: 1,
            orderId: 4
          },
          {
            displayName: '按时间查询',
            fieldName: 'time',
            formType: 'datetime',
            placeHolder: '请输入关联编号',
            // defaultTime: ["00:00:00", "23:59:59"],
            isExport: false,
            isSystem: 1,
            orderId: 5
          },
          {
            displayName: '选择状态',
            fieldName: 'status',
            formType: 'select',
            placeHolder: '请输入关联编号',
            isExport: false,
            setting: {
              isMulti: false,
              dataSource: [
                {
                  text: '全部',
                  value: ''
                },
                {
                  text: '成功',
                  value: 'succ_send'
                },
                {
                  text: '失败',
                  value: 'fail_send'
                },
                {
                  text: '发送中',
                  value: 'doing_send'
                }
              ]
            },
            isSystem: 1,
            orderId: 6
          }
        ]
      ).sort((a, b) => a.orderId - b.orderId);
    },
  },
  filters: {
    formatDate(val) {
      if (!val) return '';
      return formatDate(val, 'YYYY-MM-DD HH:mm:ss');
    }
  },
  mounted() {
    this.$nextTick(()=>{
      this.columns = this.buildTableColumn();
      this.getTemplate();
      this.search();
    });
  },
  methods: {
    getChiType(type) {
      if (type == 'taskResponseHandle') {
        return '工单响应通知';
      } else if (type == 'autoReviewHandle') {
        return '工单完成通知（回访）';
      } else if (type == 'taskFinaishHandle_finish') {
        return '工单完成通知';
      } else if (type == 'taskRemarkEdit') {
        return '工单动态更新通知';
      } else if (type == 'eventCreateHandle') {
        return '新建事件通知';
      } else if (type == 'eventFinishHandle') {
        return '事件完成通知';
      } else if (type == 'eventUpdateHandle') {
        return '事件动态更新通知';
      } else if (type == 'remindMessageHandle') {
        return '定时通知';
      } else if (type == 'taskPlanSmsRemindHandle') {
        return '计划时间通知';
      } else if (type == 'sendSms2Cus') {
        return '客户短信提醒';
      } else if (type == 'sendSms2CusByPro') {
        return '产品短信提醒';
        // }else if(type == 'sendBatchSms2Cus'){
        //     type = "客户批量发送短信提醒";
        // }else if(type == 'sendBatchSms2CusByPro'){
        //     type = "产品批量发送短信提醒";
      } else if (type == 'SSP') {
        return '自助门户验证码';
      } else if (type == 'SuperAdmin') {
        return '验证码';
      } else if (type == 'taskPlanTimeRemindHandle') {
        return '工单计划时间提醒通知';
      } else if (type == 'smsTaskStartHandle') {
        return '工单开始通知';
      } else if (type == 'eventRollBackHandle') {
        return '事件回退通知';
      } else if (type == 'eventEvaluateHandle') {
        return '事件评价通知';
      } else if (type == 'eventOffHandle') {
        return '事件取消通知';
      } else if (type == 'taskCreateHandle') {
        return '新工单通知';
      } else if (type == 'taskTransferHandle') {
        return '工单被转派通知';
      } else if (type == 'taskRollBackHandle') {
        return '工单回退通知';
      } else if (type == 'taskOffHandle') {
        return '工单取消通知';
      }else if (type == 'taskEvaluateHandle') {
        return '工单评价通知';
      } else if (type == 'taskCostHandle') {
        return '工单结算通知';
      } else if (type == 'taskCloseHandle') {
        return '工单关闭通知';
      } else if (type == 'taskOverTimeHandle') {
        return '工单超时提醒通知';
      } else if (type == 'AutoReview' || type == 'autoReview') {
        return '工单完成通知(含回访)';
      } else if (type == 'OfflineNotifyWithSms') {
        return '离线通知';
      } else if (type.indexOf('trigger_') > -1) {
        return '触发器通知';
      }
      return '其他';
      
    },
    getTemplate() {
      // 获取所有的模板
      getTemplates({ pageSize: '999', pageNum: '1' }).then(res => {
        this.smsSendFields[2].setting.dataSource = [
          {
            text: '全部',
            value: ''
          },
          ...res.data.list
            .filter(
              item =>
                item.status == 'pass_approval' && item.notice == '自定义通知'
            )
            .map(item => {
              return {
                text: item.name,
                value: item.id
              };
            })
        ];
      });
    },
    showAdvancedSetting() {
      this.$refs.advanced.open(this.columns);
    },
    buildParams() {
      const sm = Object.assign({}, this.searchModel);
      let params = {
        keyword: sm.keyword,
        pageSize: sm.pageSize,
        pageNum: sm.pageNum,
        startTime: sm.startTime,
        endTime: sm.endTime,
      };

      if (Object.keys(sm.orderDetail || {}).length) {
        params.orderDetail = sm.orderDetail;
      }

      if (Object.keys(sm.moreConditions).length > 0) {
        params = {
          ...params,
          ...sm.moreConditions
        };
      }

      return params;
    },
    // 构建表格固定列
    buildTableFixedColumns() {
      // return []
      return [
        {
          label: '通知类型',
          field: 'operation',
          show: true,
          fixed: true,
          minWidth: '150px'
        },
        {
          label: '接收号码',
          field: 'phones',
          fixed: true,
          show: true
        },
        {
          label: '发送条数',
          field: 'sendNum',
          fixed: true,
          show: true
        },
        {
          label: '模板名称',
          field: 'smsTemplateName',
          fixed: true,
          show: true
        },
        {
          label: '发送时间',
          field: 'sendTime',
          fixed: true,
          show: true
        },
        {
          label: '关联编号',
          field: 'relevanceNumber',
          fixed: true,
          show: true
        },
        {
          label: '状态',
          field: 'status',
          fixed: true,
          show: true
        },
        {
          label: '说明',
          field: 'errorStatus',
          fixed: true,
          show: true
        }
      ];
    },
    // 构建表格列
    buildTableColumn() {
      let localColumns = []
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col) => (acc[col.field] = col) && acc, {});
      let baseColumns = this.buildTableFixedColumns();
      let columns = [...baseColumns].map(col => {
        let show = col.show;
        let width = col.width;
        let localField = localColumns[col.field];

        if (null != localField) {
          width = typeof localField.width == 'number' ? `${localField.width}px` : '';
          show = localField.show !== false;
        }
        col.show = show;
        col.width = width;
        col.type = 'column';

        return col;
      });

      return columns;
    },
    // 修改列状态
    columnStatusModify(event) {
      let columns = event.data || [];
      let colMap = columns.reduce(
        (acc, col) => (acc[col.field] = col) && acc,
        {}
      );

      this.columns.forEach(col => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      const columnsStatus = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width
      }));
      this.localStorageSet(
        'columnStatus',
        columnsStatus,
        PRODUCT_TEMPLATE_LIST_DATA
      );
    },
    // 页码数切换
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;

      this.localStorageSet('pageSize', pageSize, PRODUCT_TEMPLATE_LIST_DATA);
      this.search();
    },
    // 跳转
    jump(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.search();
    },
    /* 获取本地数据 */
    localStorageGet(key) {
      try {
        const dataStr = localStorage.getItem(key) || '{}';
        return JSON.parse(dataStr);
      } catch (error) {
        console.log('error: ', error);
        return {};
      }
    },
    /* 设置本地数据 */
    localStorageSet(key, value, rootKey = null) {
      try {
        if (!rootKey) {
          localStorage.setItem(key, JSON.stringify(value));
        } else {
          const data = this.localStorageGet(rootKey);

          data[key] = value;
          localStorage.setItem(rootKey, JSON.stringify(data));
        }
      } catch (err) {
        console.log('localStorageSet err', err);
      }
    },
    // 搜索
    search() {
      const params = this.buildParams();
      return getRecords(params)
        .then(res => {
          this.$refs.searchPanel.close()
          this.page = res.data;
        })
        .catch(err => {

        });
    },
    // 设置高级搜索面板 列
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
      try {
        localStorage.setItem(
          PRODUCT_TEMPLATE_LIST_ADVANCE_SEARCH_COLUMN_NUMBER,
          this.columnNum
        );
      } catch (error) {
        console.log(error);
      }
    },
    // 搜索参数恢复
    paramsSearchRevert() {
      const localStorageData = this.localStorageGet(PRODUCT_TEMPLATE_LIST_DATA);

      if (localStorageData && localStorageData.pageSize) {
        this.searchModel.pageSize = Number(localStorageData.pageSize);
      }

      const num = localStorage.getItem(
        PRODUCT_TEMPLATE_LIST_ADVANCE_SEARCH_COLUMN_NUMBER
      ) || 1;
      this.columnNum = Number(num);
    },
    panelSearchAdvancedToggle() {
      this.$refs.searchPanel.open();
      this.$nextTick(() => {
        let forms = document.getElementsByClassName('advanced-search-form');
        for (let i = 0; i < forms.length; i++) {
          let form = forms[i];
          form.setAttribute('novalidate', true);
        }
      });
    },
    /**
     * @description 全量搜索
     */
    powerfulSearch() {
      this.searchModel.pageNum = 1;
      this.searchModel.moreConditions = this.$refs.searchPanel.buildParams();
      this.search();
    },
    resetParams() {
      this.searchIncludeMoreConditions = false;
      this.searchModel = {
        keyword: '',
        pageNum: 1,
        pageSize: this.page.pageSize,
        startTime,
        endTime,
        orderDetail: {},
        moreConditions: {
          conditions: []
        }
      };

      this.$refs.searchPanel.resetParams();
      this.search();
    },
    getRowKey(row) {
      return row.id;
    },
  },
  components: {
    [SearchPanel.name]: SearchPanel,
  }
};
</script>

<style lang="scss">
.error-text {
  color: #e51c23;
}
.success-text {
  color: #0db3a6;
}
.loading-text {
  color: #259b24;
}
.base-search{
  display: flex;
  font-size: 14px;
  justify-content: space-between;
  padding: 12px 10px;
  .product-template-list-base-search-group{
    display: flex;
    justify-content: space-between;
    width: 440px;
    .el-input {
      width: 300px;
    }
  }
  .advanced-search-visible-btn{
    color: $color-primary;
    cursor: pointer;
  }

}
</style>